﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections;
using System.Collections.Generic;


namespace lxwmvc
{
    /// <summary>
    /// 单表的crud操作
    /// </summary>
    public static class tablecontroller
    {
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="pb"></param>
        public static void _init(pagebase pb)
        {

        }

        /// <summary>
        /// 增加或者编辑
        /// </summary>
        /// <param name="pb"></param>
        [layout("default_edit")]
        public static void add(pagebase pb)
        {
            string sql = "";
            int idv = pb.get<int>(pb.pk);
            if (idv > 0)
            {
                sql = "select * from " + pb.table + " where " + pb.pk + "=@0";
                var model = queryhelper.get<supermodel>(sql, idv);
                pb.autoloaddata(model);
            }
        }

        /// <summary>
        /// 列表页面
        /// </summary>
        /// <param name="pb"></param>
        [layout("default_list")]
        public static void list(pagebase pb)
        {
            string where = pb.search();
            string orderby = pb.pk + " asc";
            {
                //前面传递的排序信息
                //cn 和 ot，如果这两个有值，就直接用着两个来组合
                string cn = pb.orderbycolumn(pb.pk, pb.ordertype());
                if (!string.IsNullOrEmpty(cn))
                    orderby = cn;

                //代表外部设置了排序,只用于第一次
                if (pb.v_s("orderby").Length > 0)
                    orderby = pb.paramsvalue("orderby", false);
            }

            //sqlhelper.showpager(pb, pb.table, "*", orderby, pb.page, pb.pagesize, where);
            var pi = queryhelper.pager(pb.table, "*", orderby, pb.page, pb.pagesize, where);
            pb["pager"] = pi;
            
        }

        /// <summary>
        /// 执行相关操作
        /// </summary>
        /// <param name="pb"></param>
        [trans]
        public static void action(pagebase pb)
        {
            Action<int> fun = (id) =>
                {
                    var model = queryhelper.get<supermodel>("select * from " + pb.table + " where " + pb.pk + "=" + id);
                    model.remove(pb.pk);
                    result ret = model.table(pb.table).saveorupdate();

                    if (pb.hasjilian)
                    {
                        string[] jilians = pb.jilians;
                        var models = queryhelper.query<supermodel>(" select * from " + jilians[0] + " where " + jilians[1] + "=" + id);
                        foreach (supermodel sm in models)
                        {
                            sm[jilians[1]] = ret.identity;
                            sm.remove(supermodel.pks[jilians[0]]);
                            sm.table(jilians[0]).saveorupdate();
                        }
                    }
                };

            string flag = pb.v_s("flag").ToLower();
            int idv = pb.v_i(pb.pk);

            if (flag == "delete")
            {
                queryhelper.execute("delete from " + pb.table + " where " + pb.pk + "=" + idv);

                //得到关联信息
                //子表_子表主键_关联主表键
                if (pb.hasjilian)
                {
                    string[] jilians = pb.jilians;
                    string sql = "delete from " + jilians[0] + " where " + jilians[1] + "=" + idv;
                    queryhelper.execute(sql);
                }

            }
            else if (flag == "deleteall")
            {
                queryhelper.execute("delete from " + pb.table + " where " + pb.pk + " in(" + pb.v_s(pb.pk) + ")");
                pb.cancelview();

                if (pb.hasjilian)
                {
                    string[] jilians = pb.jilians;
                    string sql = "delete from " + jilians[0] + " where " + jilians[1] + " in(" + pb.v_s(pb.pk) + ")";
                    queryhelper.execute(sql);
                }
            }
            else if (flag == "copy")
            {
                fun(idv);
            }
            else if (flag == "copyall")
            {
                foreach (string s in pb.v_s(pb.pk).Split(','))
                {
                    if (s == "-1") continue;
                    fun(s.toint32(-1));
                }
            }

            //执行成功!
            pb.json(new { success = true, msg = "" });
        }

        /// <summary>
        /// 不用修改程序就能添加字段，添加业务
        /// </summary>
        /// <param name="pb"></param>
        [trans]
        public static void save(pagebase pb)
        {
            pb.cancelview();
            if (checkbuchongfu(pb)) return;

            var model = pb.getmodel<supermodel>();

            if (model.table(pb.table).saveorupdate().identity > 0)
                pb.back("保存成功!");
            else
                pb.back("保存失败!", false);
        }

        /// <summary>
        /// 判断不重复
        /// </summary>
        /// <param name="pb"></param>
        /// <param name="table"></param>
        /// <param name="where"></param>
        public static bool checkbuchongfu(pagebase pb,string table = "",string where = "")
        {
            if (table.isnotnull()) pb.settable(table);
            //List<int> list = new List<int>();
            //list.Sort((r1, r2) => { return r1 > r2 ? 0 : 1; });

            //排序方法 参考内容
            //http://www.cnblogs.com/supperwu/archive/2012/06/13/2548122.html

            string tishierrmsg = "请给验证唯一性的字段赋值err信息！";

            try
            {
                //唯一性校验
                string buchongfu = pb.paramsvalue("_lxw_column_buchongfu_");
                if (buchongfu.Length > 0)
                {
                    string[] nodes = buchongfu.Split(',');
                    string[] msg = pb.paramsvalue("_lxw_column_buchongfu_msg_").Split(',');
                    for (int i = 0; i < nodes.Length; i++)
                    {
                        if (string.IsNullOrEmpty(nodes[i])) continue;
                        sqlhelper.weiyixing(
                            pb.table,
                            nodes[i],
                            pb.paramsvalue(nodes[i]),
                            msg.Length > i ? (msg[i] == "" ? tishierrmsg : msg[i]) : tishierrmsg,
                            pb.pk,
                            pb.paramsvalue(pb.pk),
                            where
                            );
                    }
                }

                return false;
            }
            catch (Exception err)
            {
                pb.back(err.Message, false);
                return true;
            }
        }
    }
}